package FrameWork.PathFinding;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JPanel;

import FrameWork.PathFinding.NodeMap.Path;

public class PathfindPanel extends JPanel implements Map,MouseMotionListener{

	private static final long serialVersionUID = 1L;
	public int size = 100,scale = 5;
	private static int max = 500;
	private boolean[][] map;
	public NodeMap nodeMap = new NodeMap(this);; 
	private Path path;
	
	public PathfindPanel(){
		addMouseMotionListener(this);
		initMap();
		
		
		
	}
	public void initMap(){
		map = new boolean[size][size];
		for(int x = 0;x<size;x++){
			for(int y = 0;y<size;y++){
				map[x][y] = false;
			}
		}
		path = null;
		nodeMap.clear();
	}
	
	@Override
	public boolean getSolid(int x, int y) {
		if(x>0 && y>0 && x<size && y<size){
			return map[x][y];
		}else{
			return true;
		}
	}
	private void setSolid(int x, int y,boolean value){
		if(x>0 && y>0 && x<size && y<size){
			map[x][y] = value;
		}
	}
	@Override
	public int getWeight(int x, int y) {
		
		return 1;
	}
	@Override
	public void paint(Graphics g){
		for(int x = 0;x < size+1;x++){
			for(int y = 0;y < size+1;y++){
				if(getSolid(x, y)){
					g.setColor(Color.gray);
				}else{
					g.setColor(Color.LIGHT_GRAY);
				}
				if(nodeMap.getValue(x, y) != 0)
					g.setColor(Color.red);
				g.fillRect(x*scale, y*scale+scale, scale, scale);
			}
		}
		if(path != null){
			g.setColor(Color.GREEN);
			for(int i = 0;i < path.getSize();i++){
				g.fillRect(path.getStepX(i)*scale, path.getStepY(i)*scale+scale, scale, scale);
			}
		}
	}
	public int getTileHeight() {
		return size;
	}
	public int getTileWidth(){
		return size;
	}
	@Override
	public void mouseDragged(MouseEvent e) {
		
		int tilex = e.getX()/scale,
				tiley = e.getY()/scale-1;
		
		if(tilex>0 && tiley>0 && tilex<size && tiley<size){
			if(e.isShiftDown()){
				setSolid(tilex, tiley, true);
				setSolid(tilex+1, tiley, true);
				setSolid(tilex-1, tiley, true);
				setSolid(tilex, tiley+1, true);
				setSolid(tilex, tiley-1, true);
			}
			else if(e.isControlDown()){
				setSolid(tilex, tiley, false);
				setSolid(tilex+1, tiley, false);
				setSolid(tilex-1, tiley, false);
				setSolid(tilex, tiley+1, false);
				setSolid(tilex, tiley-1, false);
			}
			else{
				//nodeMap.clear();
				path = nodeMap.run(5, 5,tilex,tiley, max);
			}
			repaint();
		}
	}
	@Override
	public void mouseMoved(MouseEvent e) {
		
		
	}

}
